package com.nnnu.wsnackshop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nnnu.wsnackshop.exception.ObjectException;
import com.nnnu.wsnackshop.mapper.RolePermissionsMapper;
import com.nnnu.wsnackshop.pojo.dto.AddPermissionDTO;
import com.nnnu.wsnackshop.pojo.dto.PermissionPageDTO;
import com.nnnu.wsnackshop.pojo.dto.UpdatePermissionDTO;
import com.nnnu.wsnackshop.pojo.entity.Permissions;
import com.nnnu.wsnackshop.mapper.PermissionsMapper;
import com.nnnu.wsnackshop.pojo.entity.RolePermissions;
import com.nnnu.wsnackshop.pojo.vo.PermissionVO;
import com.nnnu.wsnackshop.result.PageResult;
import com.nnnu.wsnackshop.service.IPermissionsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.lang.Collections;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@Service
@RequiredArgsConstructor
public class PermissionsServiceImpl extends ServiceImpl<PermissionsMapper, Permissions> implements IPermissionsService {
    private final PermissionsMapper permissionMapper;
    private final RolePermissionsMapper rolePermissionMapper;

    @Override
    public PageResult<PermissionVO> pagePermissions(PermissionPageDTO dto) {
        Page<Permissions> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        Page<Permissions> result = permissionMapper.selectPage(page,
                new LambdaQueryWrapper<Permissions>().like(StrUtil.isNotBlank(dto.getName()),
                        Permissions::getName, dto.getName()));
        List<PermissionVO> vos = result.getRecords().stream().map(p ->
                BeanUtil.copyProperties(p, PermissionVO.class)).collect(Collectors.toList());
        return PageResult.<PermissionVO>builder()
                .total(result.getTotal())
                .items(vos)
                .build();
    }

    @Override
    public PermissionVO getPermissionDetail(Long id) {
        Permissions p = permissionMapper.selectById(id);
        if (p == null) throw new ObjectException("权限不存在");
        return BeanUtil.copyProperties(p, PermissionVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPermission(@NotNull AddPermissionDTO dto) {
        // 唯一性校验
        if (permissionMapper.exists(
                new LambdaQueryWrapper<Permissions>()
                        .eq(Permissions::getName, dto.getName()))) {
            throw new ObjectException("权限标识已存在");
        }
        Permissions p = BeanUtil.copyProperties(dto, Permissions.class);
        permissionMapper.insert(p);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePermission(@NotNull UpdatePermissionDTO dto) {
        Permissions p = permissionMapper.selectById(dto.getId());
        if (p == null) throw new ObjectException("权限不存在");
        p.setName(dto.getName());
        p.setDescription(dto.getDescription());
        permissionMapper.updateById(p);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePermissions(@NotNull List<Long> ids) {
        if (Collections.isEmpty(ids)) {
            throw new ObjectException("删除的id列表为空，请检查");
        }
        // 1. 校验权限是否存在
        List<Long> missing = ids.stream()
                .distinct()
                .filter(id -> permissionMapper.selectById(id) == null)
                .toList();
        if (!missing.isEmpty()) {
            throw new ObjectException("以下权限不存在，无法删除: " + missing);
        }

        // 2. 删除 role_permissions 关联
        rolePermissionMapper.delete(
                new LambdaUpdateWrapper<RolePermissions>()
                        .in(RolePermissions::getPermissionId, ids)
        );

        // 3. 删除 permissions 表记录
        permissionMapper.deleteBatchIds(ids);
    }


}
